package org.fastsyncer.manager.splitter.impl;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.manager.splitter.Splitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//声明一个final，使别人不能随便new对象
//它只被调用一次，实例存在之后就不再调用了
public final class LdapSplitter implements Splitter {

    // 实现单例模式的方法，通过方法来实现实例化
    // 声明一个私有的静态属性，使只被实例化一次
    private static volatile LdapSplitter instance = null;

    private LdapSplitter() {
    }

    // 声明一个公共的静态方法，外界通过调用这个方法来得到唯一的实例
    public static LdapSplitter getInstance() {
        if (null == instance) {
            synchronized (LdapSplitter.class) {
                if (null == instance) {
                    instance = new LdapSplitter();
                }
            }
        }
        return instance;
    }

    private static Logger logger = LoggerFactory.getLogger(LdapSplitter.class);

    @Override
    public Queue<Integer[]> split(MappingTask mappingTask) {
        // 总数据量
        int total = mappingTask.getSourceMapping().getRowCount();
        // 完成进度(必须大于等于0)
        int completed = mappingTask.getProcessCompleted();
        logger.info("Total:" + total);
        logger.info("Completed progress:" + completed);
        // Ldap暂时没有分页的解决方案，目前考虑一次性读取所有数据
        if (total < 1 || completed > 0) {
            return null;
        }

        // 拆分小任务
        Queue<Integer[]> quene = new ConcurrentLinkedQueue<>();
        quene.offer(new Integer[] { 0, total });
        logger.info("Total number of tasks：" + 1);
        return quene;
    }

}
